package net.sunzc.takephoto.utils;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串操作工具，所有和字符串操作相关的方法到放置到此类 工具方法尽量保持独立，尽量不要和外部的其他类型、对象、方法等耦合，便于移植
 *
 * @author 李延超 20141215
 */
public final class StringUtils {

    private static String hexString = "0123456789ABCDEF";

    /**
     * 生成从0到end之间的随机整数
     *
     * @param start 随机数最小数
     * @param end   随机数最大数
     * @return
     */
    public static int generateRandom(int start, int end) {
        Random random = new Random();
        return random.nextInt(end) % (end - start + 1) + start;
    }

    public static String kemu(String str) {
        return "2".equals(str) ? "科目二" : ("3".equals(str) ? "科目三" : ("1"
                .equals(str) ? "科目一" : "科目四"));
    }

    public static boolean isEmpty(String str) {
        return str == null || str.trim().equals("");
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 手机号正则表达式匹配
     *
     * @param mobiles
     * @return 是否匹配成功
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((1[0-9][0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles.trim());
        return m.matches();
    }

    /**
     * 是否为电子邮件
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (null == email || "".equals(email))
            return false;
        Pattern p = Pattern.compile("[a-zA-Z0-9_-]+@\\w+\\.[a-z]+(\\.[a-z]+)?");// 复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /* String类型强转为int */
    public static int StringToInt(String str, int defaultVaule) {
        MyLog.v("mskgq", "StringToInt收到参数为" + str);
        int result = defaultVaule;
        try {
            result = Integer.valueOf(str);
        } catch (Exception e) {
        }
        return result;
    }

    /* String类型强转为int */
    public static long StringTolong(String str, long defaultVaule) {
        MyLog.v("mskgq", "StringTolong收到参数为" + str);
        long result = defaultVaule;
        try {
            result = Long.valueOf(str);
        } catch (Exception e) {
        }
        return result;
    }

    /* String类型强转为float */
    public static float StringToFloat(String str, float defaultVaule) {
        float result = defaultVaule;
        try {
            result = Float.valueOf(str);
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 取double数据后面两位小数的上界
     */
    public static double getValueWith2Suffix(double dbl) {
        dbl = dbl * 1000;
        BigDecimal bg = new BigDecimal(dbl);
        return bg.setScale(2, BigDecimal.ROUND_CEILING).doubleValue();
    }

    /*
        * 将字符串编码成16进制数字,适用于所有字符（包括中文）
        */
    public static String encode(String str) {
        // 根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    /*32383235323332303237323532383235
        *32383100000000000000000000000000
        * 将16进制数字解码成字符串,适用于所有字符（包括中文）
        */
    public static String decode(String bytes) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(
                bytes.length() / 2);
        // 将每2位16进制整数组装成一个字节
        for (int i = 0; i < bytes.length(); i += 2)
            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
                    .indexOf(bytes.charAt(i + 1))));
        return new String(baos.toByteArray());
    }

    public static String encryption(String sfz) {
        CharacterIterator ci = new StringCharacterIterator(sfz.substring(0, 17));
        int[] nums = new int[17];// 创建一个数组， 他的长度等于字符串的长度
        int i = 0;
        for (char ch = ci.first(); ch != CharacterIterator.DONE; ch = ci.next()) {
            // 判断当前字符是否为数字
            if (Character.isDigit(ch)) {
                int n = Integer.parseInt(String.valueOf(ch));
                n = n + 1;
                if (n == 10) {
                    n = 0;
                }
                nums[i++] = n;
            }
        }
        nums = swap(nums);
        StringBuffer str = new StringBuffer();
        for (int num : nums) {
            str = str.append(num);
        }
        sfz = str.toString() + sfz.substring(17);
        StringBuilder s1 = new StringBuilder(sfz);
        for (int index = 1; index < s1.length(); index += 2) {
            int result = new Random().nextInt(10);
            s1.insert(index, result);
        }
        return s1.toString();
    }

    //20273592390724010926149138461494
    public static String decrypt(String sfz) {
        StringBuilder s1 = new StringBuilder(18);
        for (int i = 1; i <= sfz.length(); i++) {
            if (i % 2 != 0) {
                s1.append(sfz.charAt(i - 1));
            }
        }
        CharacterIterator ci = new StringCharacterIterator(s1.toString().substring(0, 17));
        int[] nums = new int[17];// 创建一个数组， 他的长度等于字符串的长度
        int m = 0;
        for (char ch = ci.first(); ch != CharacterIterator.DONE; ch = ci.next()) {
            // 判断当前字符是否为数字
            if (Character.isDigit(ch)) {
                int n = Integer.parseInt(String.valueOf(ch));
                n = n - 1;
                if (n == -1) {
                    n = 9;
                }
                nums[m++] = n;
            }
        }
        nums = swap(nums);
        StringBuffer str = new StringBuffer();
        for (int num : nums) {
            str = str.append(num);
        }
        sfz = str.toString() + s1.toString().substring(17);
        return sfz;
    }

    /**
     * 交换头和尾两个值
     *
     * @param nums
     */
    private static int[] swap(int[] nums) {
        // 判断数组是否足够大，如果元素小于1则没有交换的可能
        if (nums.length > 1) {
            int len = nums.length - 1;
            int tmp = nums[0];
            nums[0] = nums[len];
            nums[len] = tmp;
        }
        return nums;
    }

    /**
     * desc:将数组转为16进制
     * <P>创建人：尹龙峰 , 2014-7-29 上午11:08:33</P>
     *
     * @param bArray
     * @return modified:
     */
    public static String bytesToHexString(byte[] bArray) {
        if (bArray == null) {
            return null;
        }
        if (bArray.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder(bArray.length);
        String sTemp;
        for (byte aBArray : bArray) {
            sTemp = Integer.toHexString(0xFF & aBArray);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * desc:将16进制的数据转为数组
     * <P>创建人：尹龙峰 , 2014-7-29 上午11:08:33</P>
     *
     * @param data
     * @return modified:
     */
    public static byte[] StringToBytes(String data) {
        String hexString = data.toUpperCase().trim();
        if (hexString.length() % 2 != 0) {
            return null;
        }
        byte[] retData = new byte[hexString.length() / 2];

        for (int i = 0; i < hexString.length(); i++) {
            int int_ch, int_ch1;
            char hex_char1 = hexString.charAt(i);
            if (hex_char1 >= '0' && hex_char1 <= '9')
                int_ch1 = (hex_char1 - 48) * 16;   //// 0 的Ascll - 48
            else if (hex_char1 >= 'A' && hex_char1 <= 'F')
                int_ch1 = (hex_char1 - 55) * 16; //// A 的Ascll - 65
            else
                return null;
            i++;
            char hex_char2 = hexString.charAt(i); ///两位16进制数中的第二位(低位)
            int int_ch2;
            if (hex_char2 >= '0' && hex_char2 <= '9')
                int_ch2 = (hex_char2 - 48); //// 0 的Ascll - 48
            else if (hex_char2 >= 'A' && hex_char2 <= 'F')
                int_ch2 = hex_char2 - 55; //// A 的Ascll - 65
            else
                return null;
            int_ch = int_ch1 + int_ch2;
            retData[i / 2] = (byte) int_ch;//将转化后的数放入Byte里
        }
        return retData;
    }

    public static <T> boolean isNull(T[] data) {
        return data == null || data.length <= 0;
    }

    public static boolean isNull(byte[] bytes) {
        return bytes == null || bytes.length <= 0;
    }

    public static boolean isNull(List list) {
        return list == null || list.isEmpty();
    }

    /**
     * Int值字节数组
     *
     * @param nSend int值
     * @return
     */
    public static byte[] Int2Bytes(int nSend) {
        byte[] pbTemp = new byte[4];

        for (int i = 0; i < 4; i++) {
            pbTemp[i] = (byte) ((nSend >> (i * 8)) & 0xff);

        }
        return pbTemp;
    }
}
